package com.cc.ttsreader

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.provider.Settings.Global.getString
import androidx.core.app.NotificationCompat

const val CHANNEL_ID = "tts_reader"
fun Context.createNotification(): Notification {
    val builder = NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.mipmap.ic_launcher)
        .setContentTitle(getString(R.string.app_name))
        .setContentText("正在播放")
        .setPriority(NotificationCompat.PRIORITY_HIGH)
    return builder.build()
}

fun Context.createNotificationChannel(): NotificationManager {
    val notificationManager: NotificationManager =
        getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val name = getString(R.string.channel_name)
        val descriptionText = getString(R.string.channel_description)
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
            description = descriptionText
        }
        // Register the channel with the system

        notificationManager.createNotificationChannel(channel)
    }
    return notificationManager
}

const val SP_NAME = "tts_reader"
const val KEY_LAST_FILE = "last_file"
const val KEY_LAST_POSITION = "last_position"
fun Context.getLastFilePath(): String? {
    return getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).getString(KEY_LAST_FILE, "")
}

fun Context.setCacheFile(path: String?) {
    getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).edit().putString(KEY_LAST_FILE, path)
        .apply()
}

fun Context.getLastPosition(): Int {
    return getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).getInt(
        KEY_LAST_POSITION, 0
    )
}

fun Context.setLastPosition(position: Int) {
    getSharedPreferences(SP_NAME, Context.MODE_PRIVATE).edit().putInt(KEY_LAST_POSITION, position)
        .apply()
}